package com.iori.common.db.extend;

import java.sql.Connection;

import com.iori.common.db.TranStatementController;
import com.iori.common.log.FounderLog;
import com.iori.common.log.LogFactory;

/**
 * 事務工廠，負責事務的啓動、釋放
 *
 * @author zheng_linxi
 *
 */
public class ControllerFactory {

	public static final ThreadLocal session = new ThreadLocal();

	public static final ThreadLocal connSession = new ThreadLocal();

	private static FounderLog log = LogFactory.getFounderLog(ControllerFactory.class);
	/**
	 * 启动TranStatementController
	 *
	 * @return
	 */
	public static TranStatementController currentController() {

		TranStatementController ts = (TranStatementController) session.get();
		if (ts == null) {
			ts = new TranStatementController();
			session.set(ts);
		}
		return ts;
	}

	public static void rollback(){

	}

	/**
	 *
	 * 结束TranStatementController
	 */
	public static void closeController() {

		session.remove();

	}

	public static Connection getConnection() {
		Connection conn = (Connection) connSession.get();
		if (conn == null) {
			try {

				conn = TranStatementController.beginTransaction();
				connSession.set(conn);

			} catch (Exception e) {
				// TODO 自动生成 catch 块
//				e.printStackTrace();
				log.error(e.getMessage());
			}
		}
		return conn;
	}

	public static Connection getConnection(String datebaseName) {
		Connection conn = (Connection) connSession.get();
		if (conn == null) {
			try {

				conn = TranStatementController.beginTransactionEx(datebaseName);
				connSession.set(conn);

			} catch (Exception e) {
				// TODO 自动生成 catch 块
				//e.printStackTrace();
				log.error(e.getMessage());
			}
		}
		return conn;
	}

	public static void closeConn() {
		connSession.remove();

	}
}
